package com.tuvi.nhamthin.activity;

import com.tuvi.nhamthin.R;
import com.tuvi.nhamthin.api.ITuvi;
import com.tuvi.nhamthin.api.TuviApi;
import com.tuvi.nhamthin.common.DeviceFactory;
import com.tuvi.nhamthin.dialog.ActiveDialog;
import com.tuvi.nhamthin.dialog.ChonGoiTinh;
import com.tuvi.nhamthin.entity.GiapItem;
import com.tuvi.nhamthin.helper.SqlHelper;
import com.tuvi.nhamthin.services.BackgroundMusic;

import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Active extends  BaseActivity{

	/** Button Back */
    private ImageButton mBtnBack;
    private SqlHelper dbHelper = null;
    private Cursor mAgeCursor;
    private String name;
    private int gender;
    private ImageView mAgeImage;
    private TextView mAge;
    private TextView mAgeDetail;
    private ImageButton mBtnSendMess;
    private ImageButton mSendSms;
    private Context mContext;
    public static String errorMessage= null;
    //private EditText mKeyActive;
    
    public boolean sendSMS() {
    	PendingIntent pi1 = PendingIntent.getActivity(this, 0,
                new Intent(this, Active.class), 0);                
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage("0979335306", null, "Binh kute", pi1, null);        
    	return true;
    }
	  /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle paramBundle)
    {
      super.onCreate(paramBundle);
      requestWindowFeature(Window.FEATURE_NO_TITLE);
      setContentView(R.layout.active);
      mContext = this.getApplicationContext();
      mAgeImage = (ImageView) findViewById(R.id.left_image);
      mAge = (TextView) findViewById(R.id.age);
      mAgeDetail = (TextView) findViewById(R.id.detail);
      mBtnSendMess = (ImageButton) findViewById(R.id.btn_sendMess);
      //mKeyActive = (EditText) findViewById(R.id.key_active);
      mSendSms =(ImageButton)findViewById(R.id.sms_btn);
      Intent intent = getIntent();
      this.name = intent.getStringExtra("name");
      this.gender = intent.getIntExtra("gender", -1);
      startService(new Intent(this, BackgroundMusic.class));
      mBtnBack = (ImageButton) findViewById(R.id.btn_back);
      if (this.dbHelper == null) {
			this.dbHelper = new SqlHelper(this);
			
		}
      mAgeCursor = dbHelper.getAgeInfo(this.name);
      startManagingCursor(mAgeCursor);
      mAgeCursor.moveToFirst();
      GiapItem item = new GiapItem(
    		  mAgeCursor.getString(mAgeCursor
						.getColumnIndex(SqlHelper.COLUMN_NAME)),
				mAgeCursor.getString(mAgeCursor
						.getColumnIndex(SqlHelper.COLUMN_FULLNAME)),
				mAgeCursor.getString(mAgeCursor
						.getColumnIndex(SqlHelper.COLUMN_DESCRIPTION)),
				null,
				mAgeCursor.getString(mAgeCursor.getColumnIndex(SqlHelper.COLUMN_PARENT)),
				null,
				null,
				null,
				null,
				mAgeCursor.getString(mAgeCursor
						.getColumnIndex(SqlHelper.COLUMN_IMAGE_ICON)));
      int i = mAgeCursor.getCount();
      mAge.setText(item.getFullName());
      mAgeDetail.setText(item.getDescription());
      String image = item.getImage_icon().toLowerCase();
      String parent = item.getParent();
//      int resd = this.getResources().getIdentifier(image, "drawable", this.getPackageName());
//      mAgeImage.setImageResource(resd);
      if (parent.equals("Ty")) {
    	  mAgeImage.setImageResource(R.drawable.ty);
      }
      if (parent.equals("Suu")) {
    	  mAgeImage.setImageResource(R.drawable.suu);
      }
      if (parent.equals("Dan")) {
    	  mAgeImage.setImageResource(R.drawable.dan);
      }
      if (parent.equals("Mao")) {
    	  mAgeImage.setImageResource(R.drawable.mao);
      }
      if (parent.equals("Thin")) {
    	  mAgeImage.setImageResource(R.drawable.thin);
      }
      if (parent.equals("Tyj")) {
    	  mAgeImage.setImageResource(R.drawable.tyj);
      }
      if (parent.equals("Ngo")) {
    	  mAgeImage.setImageResource(R.drawable.ngo);
      }
      if (parent.equals("Mui")) {
    	  mAgeImage.setImageResource(R.drawable.mui);
      }
      if (parent.equals("Than")) {
    	  mAgeImage.setImageResource(R.drawable.than);
      }
      if (parent.equals("Dau")) {
    	  mAgeImage.setImageResource(R.drawable.dau);
      }
      if (parent.equals("Tuat")) {
    	  mAgeImage.setImageResource(R.drawable.tuat);
      }
      if (parent.equals("Hoi")) {
    	  mAgeImage.setImageResource(R.drawable.hoi);
      }

      
      //openActiveAlert();
      
      mBtnBack.setOnClickListener(new OnClickListener() {
    	    public void onClick(View v) {
    	       // your code here
    	    	finish();
    	    }
    	});
      mBtnSendMess.setOnClickListener(new OnClickListener() {
  	    public void onClick(View v) {
  	    	activeKey();
  	    }
  	});
      
      mSendSms.setOnClickListener(new OnClickListener() {
  	    public void onClick(View v) {
  	       // your code here
  	    	openActiveDialog();
  	    }
  	});
    }
    public void activeKey(){
    	EditText key = (EditText)findViewById(R.id.key_code);
    	String key1 = key.getText().toString();
    	if (key1.length()==0) {
			Toast alert = Toast.makeText(this,getString(R.string.empty_code), 1000);
			alert.show();
		}else{
			//if (checkLocalKey(key1)) {
		    	ActiveAsyncTask task = new ActiveAsyncTask(this, key1);
		    	task.execute();
			//}else{
 			//	Toast alert1 = Toast.makeText(mContext, mContext.getString(R.string.key_duplicate), 1000);
 			//	alert1.show();
			//}
		}
    }
    private boolean checkLocalKey(String key){
    	SqlHelper sql = new SqlHelper(this);
		return sql.isOtherExist(key);
    }
    public void openActiveDialog() {
    	 ActiveDialog mActiveDialog = new ActiveDialog(this);
    	 mActiveDialog.show();
    }
    private void openActiveAlert(){
    	ActiveDialog alert = new ActiveDialog(this);
    	alert.setCanceledOnTouchOutside(true);
    	alert.show();
    }
    class ActiveAsyncTask extends AsyncTask<Void, Void, Void> {
    	private ProgressDialog mProgressDialog;
    	private Context mContext;
    	private String keycode;
    	private boolean success = false;
    	public ActiveAsyncTask(Context mContext, String keycode){
    		this.mContext = mContext;
    		this.keycode = keycode;
    	}
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog = ProgressDialog.show(mContext, "",
                    getString(R.string.loading), true);
        }
		@Override
		protected Void doInBackground(Void... paramArrayOfParams) {
			// TODO Auto-generated method stub
			success = registerToServer();
			return null;
		}
        @Override
        protected void onPostExecute(Void result) {
        	super.onPostExecute(result);
        	 mProgressDialog.dismiss();
        	 if (success) {
 				//Save to database
        		EditText key = (EditText)findViewById(R.id.key_code);
 				SqlHelper sqlHelper = new SqlHelper(mContext);
 				String UUIDEncoded;
				try {
					UUIDEncoded = DeviceFactory.md5(DeviceFactory.getDeviceId(mContext));
	 				sqlHelper.addCard(name, gender, key.getText().toString(), UUIDEncoded);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
 				Toast alert = Toast.makeText(mContext, mContext.getString(R.string.active_success), 1000);
 				alert.show();
 				Intent detail = new Intent(mContext, AgeDetail.class);
 				detail.putExtra("htmlName", name.toLowerCase()+"_"+gender);
 				mContext.startActivity(detail);
 			}else{
 				if(Active.errorMessage == null){
					Toast alert1 = Toast.makeText(mContext,
							mContext.getString(R.string.invalid_code), 1000);
					alert1.show();
 				}else{
					Toast alert1 = Toast.makeText(mContext,
							Active.errorMessage, 1000);
					alert1.show();
 				}
 			}
        }
        private boolean registerToServer(){
        	ITuvi api = new TuviApi();
        	return api.validateActiveCode(TuviApi.USERNAME,
        			TuviApi.PASSWORD, 
        			TuviApi.APP_ID, 
        			keycode, 
        			DeviceFactory.getDeviceId(mContext));
        }
    }
}
